const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const WorkboxPlugin = require('workbox-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, './', dir)
}

function getOutputFolder(MODE_ENV) {
  switch (MODE_ENV) {
    case 'dev':
      return 'assistant-student-app-xuxin'
    case 'test':
      return 'assistant-student-app-aizjtest'
    case 'pro':
      return 'assistant-student-app-aizj'
    default:
      return 'assistant-student-app'
  }
}

module.exports = (env) => {
  return {
    entry: {
      redirect: './modules/redirect/index.js',
      app: './src/main.js',
      homework: './modules/homework/index.js',
      wqBook: './modules/wq-book/index.js',
      exercise: './modules/exercise/index.js',
      learning: './modules/learning/index.js',
      photoSearch: './modules/photoSearch/index.js',
      contact: './modules/contact/index.js',
      dict: './modules/dict/index.js'
    },
    output: {
      path: path.resolve(__dirname, `student_web/${getOutputFolder(env.MODE_ENV)}`),
      filename: '[name].[contenthash].js',
      publicPath: '/assistant-student-app/'
    },
    optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 0,
        cacheGroups: {
          // 缓存模块,会增加service worker初始化缓存时间
          // vendor: {
          //   test: /[\\/]node_modules[\\/]/,
          //   name(module) {
          //     //取得名称。例如 /node_modules/packageName/not/this/part.js
          //     // 或 /node_modules/packageName
          //     const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
          //
          //     // npm package 是 URL 安全的，但有些服务不喜欢 @ 符号
          //     return `npm.${packageName.replace('@', '')}`
          //   }
          // }
        }
      }
    },
    resolve: {
      extensions: ['.js', '.vue', '.json','.png'],
      alias: {
        vue$: 'vue/dist/vue.esm.js',
        '@': resolve('src')
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_moduels/,
          use: {
            loader: 'babel-loader'
          }
        },
        //打包vue文件
        {
          test: /\.vue$/,
          loader: 'vue-loader'
        },
        //打包css文件
        {
          test: /\.css$/,
          use: [
            'style-loader',
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false,
                publicPath: '../../'
              }
            },
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: [
                  require('postcss-pxtorem')({
                    rootValue: 100,
                    propList: ['*']
                  })
                ]
              }
            }
          ]
        },
        //打包scss文件
        {
          test: /\.scss$/,
          use: [
            'style-loader',
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false,
                publicPath: '../../'
              }
            },
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: [
                  require('postcss-pxtorem')({
                    rootValue: 100,
                    propList: ['*']
                  })
                ]
              }
            },
            'sass-loader',
            {
              loader: 'sass-resources-loader',
              options: {
                sourceMap: true,
                resources: ['./src/styles/mixin.scss']
              }
            }
          ]
        },
        {
          test: /\.(jpg|png|gif)$/,
          loader: 'url-loader',
          options: {
            limit: 8 * 1024,
            esModule: false
          }
        },
        {
          test: '/.html$/',
          loader: 'html-loader'
        },
        {
          test: /\.(htm|html)$/i,
          use: ['html-withimg-loader']
        },
        {
          test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
          loader: 'file-loader',
          options: {
            limit: 10000,
            name: 'static/fonts/[name].[hash:7].[ext]'
          }
        }
      ]
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.MODE_ENV': JSON.stringify(env.MODE_ENV)
      }),
      new CopyWebpackPlugin([
        {
          from: path.resolve(__dirname, './public'),
          to: 'static'
        }
      ]),
      new CleanWebpackPlugin(),
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: './modules/redirect/index.html',
        filename: 'redirect.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['redirect']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'index.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['app']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'homework.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['homework']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'wq-book.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['wqBook']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'exercise.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['exercise']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'learning.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['learning']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'photoSearch.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['photoSearch']
      }),
      new HtmlWebpackPlugin({
        template: './index.html',
        filename: 'contact.html',
        favicon: './src/assets/logo.png',
        inject: true,
        chunks: ['contact']
      }),
      new MiniCssExtractPlugin({
        filename: 'static/css/[name].css'
      }),
      new WorkboxPlugin.InjectManifest({
        // 目前的service worker 文件
        swSrc: './src/workbox/sw-redirect.js',
        // 打包后生成的service worker文件，一般存到disk目录
        swDest: './sw-redirect.js'
      })
    ],
    devServer: {
      contentBase: path.resolve(__dirname, 'build'),
      compress: true,
      port: 3000,
      open: true,
      openPage: 'assistant-student-app/',
      https: true
    }
  }
}
